const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 3000;

// Video directory - change this to your videos directory
const VIDEO_DIR = '/huijie2025';

app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../public')));

// Serve video files
app.use('/videos', express.static(VIDEO_DIR));

// API to get directory structure
app.get('/api/videos', (req, res) => {
  const dirPath = req.query.path ? path.join(VIDEO_DIR, req.query.path) : VIDEO_DIR;
  
  // Make sure the path is within the VIDEO_DIR to prevent directory traversal
  if (!dirPath.startsWith(VIDEO_DIR)) {
    return res.status(403).json({ error: 'Access denied' });
  }
  
  try {
    const items = fs.readdirSync(dirPath, { withFileTypes: true });
    const result = items.map(item => {
      const isDirectory = item.isDirectory();
      const relativePath = path.join(req.query.path || '', item.name);
      
      // Only include video files (basic extension checking)
      const isVideo = !isDirectory && ['.mp4', '.webm', '.mkv', '.avi', '.mov', '.flv', '.wmv'].includes(
        path.extname(item.name).toLowerCase()
      );
      
      return {
        name: item.name,
        path: relativePath,
        isDirectory,
        isVideo
      };
    });
    
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Create videos directory if it doesn't exist
if (!fs.existsSync(VIDEO_DIR)) {
  fs.mkdirSync(VIDEO_DIR, { recursive: true });
  console.log(`Created video directory: ${VIDEO_DIR}`);
}

app.listen(PORT, HOST, () => {
  console.log(`Server running on http://${HOST}:${PORT}`);
  console.log(`Serving videos from: ${VIDEO_DIR}`);
}); 
